

import socket, os
import pyev
import signal
import struct
from route import Route
from cStringIO import StringIO

STOPSIGNALS = (signal.SIGINT, signal.SIGTERM)



'''
port ==> tcppot ==> route ==> module

                       port <==


'''
class TCPPort:
  def __init__(self):
    self.route = Route()
    self.loop = pyev.default_loop()

  def start():
     for sig in STOPSIGNALS:
      watcher = pyev.Signal(sig, self.loop, self.signal_cb)
      watcher.start()

    self.loop.start()

  def bind_unix_socket(self, filename):
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.connect(filename)
    sock.setblocking(0);
    self.sock = sock
    watcher = pyev.Io(self.sock, pyev.EV_READ, self.loop, self.io_cb
        );
    watcher.start()
    self.watcher = watcher


  def io_cb(self, watcher, revents):
    if revents & pyev.EV_READ:
      self.handle_read()
    else:
      self.handle_write()

  def handle_read(self,):
    data = self.sock.recv(1024)

  def close(self):
    self.sock.close()
    self.watcher.stop()
    self.watcher = None

  def signal_cb(self, watcher, revents):
    loop.stop(pyev.EVBREAK_ALL);



  def dispatch_packet(self, packet):
    msgid = packet.msgid




